package sm.server.requestOperations;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.rmi.NotBoundException;

import sm.namingservice.ServerState;
import sm.namingservice.ServerTable;
import sm.server.serverlist.ServerList;
import sm.utils.Message;
import sm.utils.PropertySet;

public class RequestHandler extends Thread{
	private Socket sk;
	private ServerTable st;
	private ServerState ss;
	private String request;
	
	public RequestHandler(Socket sk,ServerTable st,ServerState ss){
		this.sk = sk;
		this.st = st;
		this.ss = ss;
	}
	
	public void run(){
		BufferedReader in = null;
		DataOutputStream out = null;
		
		try{
			in = new BufferedReader(new InputStreamReader(sk.getInputStream()));
			out = new DataOutputStream(sk.getOutputStream());
			Message result = new Message();
			while(true){
				String request = in.readLine();
				if(request!=null){
					System.out.println("Request: " + this.request);
				
					Message msg = new Message().parse(request);
					
					//call operations according to request data
					if(msg.checkValidity() && msg.getCommand().equals(PropertySet._cmdGetGws)){
						String[] serverList = ServerList.getASList();
						String msgData = new String("");
						for(String curServer:serverList){
							String curSS = ss.getDwsState(curServer);
							if(curSS.equals(PropertySet._powerOn)){
								msgData = msgData + st.getAddress(curServer)+PropertySet._msgDataSplit;
							}
						}
						result.setId(msg.getId());
						result.setHeader(new String("response"));
						result.setCommand(msg.getCommand());
						result.setData(msgData);
					}
					//reply to client
					out.writeBytes(result.toString());
					out.flush();
					System.out.println(result.toString());
					System.out.println("Response Sent.");
				}
			}
		}catch (IOException e)  
	    {  
		       System.out.println (e.toString ());  
		}finally{
			try{
				if(in!=null) in.close();
				if(out!=null) out.close();
				if(sk !=null) sk.close();
			}catch(IOException e){
				System.out.println (e.toString ()); 
			}
		}
	}
}
